import { bArr2hexdump, bArr2str } from "./castTools"
import { print_stacks } from "./Tools"

/**
 * Dump UDP, 目前有Bug
 * @param {Array} ipFilter IP过滤
 * @param {Array} dataFilter 数据内容过滤
 */
function UDPDump(ipFilter = [], dataFilter = []) {
    var DatagramSocket = Java.use("java.net.DatagramSocket")
    function dealSock(udpSock, sv = "s") {
        try {
            const addr = udpSock.getAddress()
            if (!addr) {
                return
            }
            const host = addr.getHostName()
            if (sv == "s") {
                console.warn("<--", host + ":" + udpSock.getPort() + " <" + udpSock.getLength() + ">")
            } else {
                console.warn("-->", host + ":" + udpSock.getPort() + " <" + udpSock.getLength() + ">")
            }
            if (ipFilter.includes(host)) {
                return
            }
            // 打印 payload
            console.log(bArr2hexdump(udpSock.getData(), udpSock.getLength()))

        } catch (e) {
            console.error(e)
        }

    }
    var UDPsend = DatagramSocket.send
    UDPsend.implementation = function () {
        // print_stacks()
        var udpSock = arguments[0]
        dealSock(udpSock)
        // console.log(send_data)
        UDPsend.call(this, arguments[0])
    }

    var UDPrecv = DatagramSocket.receive
    UDPrecv.implementation = function () {
        UDPrecv.call(this, arguments[0])
        var recvSock = arguments[0]
        dealSock(recvSock)
    }
}

export { UDPDump }